package com.kg.elysia.controller;

import com.kg.elysia.db.Mural;
import com.kg.elysia.service.MuralService;
import com.kg.elysia.service.Neo4jService;
import com.kg.elysia.utils.ExcelParser;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.file.OpenOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.RoutingContext;
import io.vertx.mysqlclient.MySQLBatchException;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *
 * </p>
 *
 * @author zj
 * @since 2025/10/20 15:29
 */
public class ExcelController {

    private final Vertx vertx;
    private final MuralService muralService;
    private final Neo4jService neo4jService;

    public ExcelController(Vertx vertx, MuralService muralService) {
        this.vertx = vertx;
        this.muralService = muralService;
        this.neo4jService = new Neo4jService(vertx);
    }

    public void handleUpload(RoutingContext ctx) {
        FileUpload upload = ctx.fileUploads().getFirst();
        vertx.fileSystem().readFile(upload.uploadedFileName())
                .onSuccess(buffer -> {
                    try (InputStream is = new ByteArrayInputStream(buffer.getBytes())) {
                        List<Mural> murals = ExcelParser.parse(is);
                        if(!murals.isEmpty()){
                            muralService.truncateMurals();
                            neo4jService.clearAllData();
                            muralService.batchAddMurals(murals)
                                    .onSuccess(count -> {
                                        ctx.response()
                                                .setStatusCode(200)
                                                .putHeader("Content-Type", "application/json")
                                                .end(new JsonObject().put("message", "Successfully uploaded " + count + " murals").encode());
                                    }).onFailure(ctx::fail);
                            neo4jService.importMurals(murals);
                        }
                    } catch (MySQLBatchException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                        ctx.fail(e);
                    }
                })
                .onFailure(ctx::fail);
    }
}
